import mysql from '../common/mysql'
import Sequelize from 'sequelize'
import bcrypt from 'bcrypt-nodejs'

const User = mysql.define('User', {
    id: {
        type: Sequelize.DataTypes.BIGINT.UNSIGNED,
        autoIncrement: true,
        primaryKey: true
    },
    username: {
        type: Sequelize.DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
            len: {
                args: [5, 20],
                msg: '用户名长度为 5 - 20'
            }
        }
        // defaultValue: ''
    },
    name: {
        type: Sequelize.DataTypes.STRING,
        allowNull: true,
        validate: {
            len: {
                args: [2, 10],
                msg: '姓名长度为 2 - 10'
            }
        }
    },
    password: {
        type: Sequelize.DataTypes.STRING,
        allowNull: true,
        defaultValue: '',
        set(val){
            bcrypt.genSalt(12, (err, salt) => {
                bcrypt.hash(val, salt, null, (err, hash) => {
                    this.setDataValue('password', hash)
                })
            })
        }
    },
    role_id: {
        type: Sequelize.DataTypes.BIGINT.UNSIGNED,
        allowNull: true
    },
    store_id: {
        type: Sequelize.DataTypes.BIGINT.UNSIGNED,
        allowNull: true
    },
    idCard:{
        type: Sequelize.DataTypes.STRING(21),
        allowNull: true,
        validate:{
            len: {
                args: [21,21],
                msg: '身份证号的长度必须为21位'
            }
        }
    }
}, {
    tableName: 'user'
})

export default User
